package com.youkeda.test.http;

import okhttp3.*;
import okhttp3.FormBody.Builder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PageLoginer {

    // 用 CookieJar 实现 cookie 的存储，便于登录后请求其它 URL 可以复用
    private static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .cookieJar(new CookieJar() {
                private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

                @Override
                public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                    cookieStore.put("mtime.com", cookies);
                }

                @Override
                public List<Cookie> loadForRequest(HttpUrl url) {
                    List<Cookie> cookies = cookieStore.get("mtime.com");
                    return cookies != null ? cookies : new ArrayList<>();
                }
            })
            .build();

    public static void main(String[] args) {
        PageLoginer asker = new PageLoginer();

        // 完成登录
        String url = "https://passport.mtime.com/member/signinLogin";
        // 登录表单数据
        Map<String, String> formData = new HashMap();
        formData.put("loginEmailText", "15538369114");
        formData.put("loginPasswordText", "20cd1620d0529463f981d8c7fcca4eae");
        formData.put("isvcode", "true");
        formData.put("isAutoSign", "false");
        String content = asker.postContent(url, formData);
        System.out.println("login result:");
        System.out.println(content);

        // 请求我的订单
        String myOrderUrl = "http://my.mtime.com/account/ecommerce/orderList/";
        String dataContent = asker.getContent(myOrderUrl);
        System.out.println(dataContent);
    }

    /**
     * 向指定的 URL 提交数据，并返回提交后的结果
     */
    public String postContent(String url, Map<String, String> formData) {
        //post方式提交的数据
        Builder builder = new FormBody.Builder();
        // 放入表单数据
        for (String key : formData.keySet()) {
            builder.add(key, formData.get(key));
        }
        // 构建 FormBody 对象
        FormBody formBody = builder.build();
        // 指定 post 方式提交FormBody
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .addHeader("User-Agent",
                        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36")
                .addHeader("Referer",
                        "https://passport.mtime.com/member/signin/?redirectUrl=http%3A%2F%2Fwww.mtime.com%2F")
                .addHeader("Host", "passport.mtime.com")
                .build();

        return doExcute(request);
    }

    /**
     * 根据输入的url，读取页面内容并返回
     */
    public String getContent(String url) {
        // 定义一个request
        Request request = new Request.Builder()
                .url(url)
                .addHeader("User-Agent",
                        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36")
                .addHeader("Refer", "https://passport.mtime.com/member/signin/?redirectUrl=http%3a%2f%2fmy.mtime.com%2faccount%2f")
                .addHeader("Host", "my.mtime.com")
                .build();
        return doExcute(request);
    }

    private String doExcute(Request request) {
        // 返回结果字符串
        String result = null;
        try {
            result = okHttpClient.newCall(request).execute().body().string();
        } catch (IOException e) {
            // 抓取异常
            System.out.println("request " + request.url() + " error . ");
            e.printStackTrace();
        }

        return result;
    }
}
